-- Librarys
awful = require("awful")
awful.autofocus = require("awful.autofocus")
awful.rules = require("awful.rules")
beautiful = require("beautiful")
drop = require("attachdrop")
gears = require("gears")
freedesktop = require("freedesktop")
lain = require("lain")
menubar = require("menubar")
minitray = require("utils/minitray")
tyrannical = require("tyrannical")
wibox = require("wibox")

-- Error handling
-- Check if awesome encountered an error during startup and fell back to
-- another config (This code will only ever execute for the fallback config)
if awesome.startup_errors then
   awful.util.spawn_with_shell(
      "notify-send -u 'critical' " ..
	 "'Oops, there were errors during startup!'" ..
	 awesome.startup_errors
   )
end

-- Handle runtime errors after startup
do
   local in_error = false
   awesome.connect_signal("debug::error", function (err)
			     -- Make sure we don't go into an endless error loop
			     if in_error then return end
			     in_error = true
			     awful.util.spawn_with_shell(
				"notify-send -u 'critical' " ..
				   "'Oops, an error happened!'" ..
				   err
			     )
			     in_error = false
   end)
end

-- {{{ Autostart applications
local function run_once(cmd)
  findme = cmd
  firstspace = cmd:find(" ")
  if firstspace then
    findme = cmd:sub(0, firstspace-1)
  end
  awful.util.spawn_with_shell(string.format("pgrep -u $USER -x %s > /dev/null || (%s)", findme, cmd))
end

run_once("clipit")
-- }}}

-- Variable Definitions
os.setlocale(os.getenv("LANG"))

-- Useful Paths
home = os.getenv("HOME")

local f = assert(io.popen('python2 -c "import os; print os.path.isdir(\'/media/data\')"'))
local ddir = f:read()
f:close()

datadir = home
datapart = "/home"
if ddir == "True" then
  datadir = "/media/data"
  datapart = datadir
end

confdir = home .. "/.config/awesome"
scriptdir = home .. "/.bin"
scr_res = "1920x1200"

-- Choose Your Theme
beautiful.init(confdir .. "/themes/Darkness/theme.lua")

-- Wallpaper
if beautiful.wallpaper then
  for s = 1, screen.count() do
    gears.wallpaper.maximized(beautiful.wallpaper, s, true)
  end
end
-- }}}

-- This is used later as the default terminal and editor to run.
terminal = scriptdir .. "/durxvt -geometry 100x30 -name Terminal -icon " .. freedesktop.utils.lookup_icon({ icon='terminal' })
ddterminal = scriptdir .. "/durxvt -pe tabbedex -name Drop-Terminal -icon " .. freedesktop.utils.lookup_icon({ icon='tilda' })
eter = terminal .. " -geometry 140x42 -name emacs -icon " .. freedesktop.utils.lookup_icon({ icon='emacs' }) .. " -e " .. scriptdir .. "/demacs "
browser = "firefox"
fileman = "dolphin " .. datadir
cfileman = terminal .. " -title Ranger -icon " .. freedesktop.utils.lookup_icon({ icon='system-file-manager' }) .. " -e ranger " .. datadir
music = terminal .. " -geometry 110x30 -title Music -icon " .. freedesktop.utils.lookup_icon({ icon='cantata' }) .. " -e ncmpcpp "
net = "nmcli_dmenu"
chat = terminal .. " -title Chat -icon " .. freedesktop.utils.lookup_icon({ icon='pidgin'  })  ..  " -e weechat "
torrent = terminal .. " -title Torrent -icon " .. freedesktop.utils.lookup_icon({ icon='transmission' }) .. " -e rtorrent "
tmux = terminal .. " -title Tmux -icon " .. freedesktop.utils.lookup_icon({ icon='utilities-terminal' }) .. " -e tmux new -s arkhan "

-- Default modkey.
-- Usually, Mod4 is the key with a logo between Control and Alt.
-- If you do not like this or do not have such a key,
-- I suggest you to remap Mod4 to another key using xmodmap or other tools.
-- However, you can use another modifier like Mod1, but it may interact with others.
modkey = "Mod4"
altkey = "Mod1"

-- Table of layouts to cover with awful.layout.inc, order matters.
local layouts = {
  awful.layout.suit.floating,
  awful.layout.suit.fair,
  awful.layout.suit.tile,
  awful.layout.suit.max,
  awful.layout.suit.max.fullscreen,
  awful.layout.suit.magnifie,
}
-- }}}

-- Tags Manage
tags = {}

-- First, set some settings
tyrannical.settings.block_children_focus_stealing = true
tyrannical.settings.group_children = true
tyrannical.settings.default_layout = lain.layout.termfair
tyrannical.settings.mwfact = 0.66

-- Setup some tags
tyrannical.tags = {
  {name = "www",
   init = true,
   exclusive = true,
   screen = {1, 2},
   select = true,
   class = {
     "Opera", "Firefox", "Iceweasel", "Light",
     "Midori", "Rekonq", "Dillo", "qutebrowser",
     "Arora", "Iron", "Chromium",
     "Google-chrome-stable", "google-chrome", "nightly",
     "minefield", "google-chrome-unstable"}},
  {name = "mail",
   init = false,
   exclusive = true,
   screen = 1,
   class = {
     "Kmail", "Kmail:New", "Kmail:Re",
     "Akonadi_imap_resource", "evolution", "Icedove",
     "Icedove:Re", "Thunderbird", "Thunderbird:Re",}},
  {name = "files",
   init = false,
   exclusive = true,
   screen = 1,
   class = {
     "Thunar", "Konqueror", "Dolphin",
     "ark", "Nautilus","emelfm",
     "URxvt:Ranger", "Dfm", "Dolphin:Move",
     "Dolphin:Copy",}},
  {name = "chat",
   init = false,
   exclusive = true,
   screen = 1,
   class = {
     "URxvt:Chat", "Telegram", "Skype",
     "qTox", "Cutegram", "TelegramDesktop"}},
  {name = "develop",
   init = false,
   exclusive = true,
   screen = 1,
   class = {
     "Kate", "KDevelop", "Codeblocks",
     "Code::Blocks" , "DDD", "kate4",
     "Geany", "jetbrains-pychar", "jetbrains-pycharm",
     "jetbrains-pycharm-ce", "jetbrains-pycharm-ce", "Atom"}},
  {name = "doc",
   init = false,
   exclusive = true,
   screen = 1,
   class = {
     "Assistant", "Okular", "Evince",
     "EPDFviewer", "xpdf", "Xpdf",
     "Zathura", "Kile", "TeXstudio"}},
  {name = "office",
   init = false,
   exclusive = true,
   screen = {1, 2},
   class = {
     "N/A", "LibreOffice 5.0", "libreoffice-startcenter",
     "libreoffice-writer", "libreoffice-calc", "libreoffice-impress",
     "libreoffice-base", "libreoffice-math", "libreoffice-draw",
     "com-almworks-launcher-Launcher", "OOWriter", "OOCalc",
     "OOMath", "OOImpress", "OOBase",
     "SQLitebrowser", "Silverun", "Workbench",
     "KWord", "KSpread", "KPres","Basket",
     "openoffice.org", "OpenOffice.*",}},
  {name = "multimedia",
   init = false,
   exclusive = true,
   screen = 1,
   class = {
     "URxvt:MPD", "Cantata",}},
  {name = "conf",
   init = false ,
   exclusive = false,
   screen = 1,
   class = {
     "Systemsettings", "Kcontrol", "gconf-editor",
     "Lxappearance", "Kwalletd"}},
  {name = "download",
   init = false ,
   exclusive = false,
   screen = 1,
   class = {
     "JDownloader", "URxvt:Torrent"}},
  {name = "fullscreen",
   init = false ,
   exclusive = false,
   screen = 1,
   layout = awful.layout.suit.max.fullscreen,
   class = {
     "Plugin-container"}},
  {name = "movie",
   init = false,
   exclusive = false,
   screen = {1, 2},
   class = {
     "MPV:Movie"}}
}

-- Ignore the tag "exclusive" property for the following clients (matched by classes)
tyrannical.properties.intrusive = {
  "xterm", "urxvt", "aterm",
  "URxvt", "XTerm", "konsole",
  "terminator", "gnome-terminal", "URxvt:Terminal",
  "URxvt:Drop", "URxvt:Tmux", "XTerm:Terminal",
  "Emacs", "Pilasengine", "URxvt:Emacs",
  "emacsclient", "Kamerka", "Keepassx2",
  "ksnapshot", "pinentry", "gtksu",
  "kcalc", "xcalc", "feh",
  "Gradient editor", "About KDE", "Paste Special",
  "Background color", "kcolorchooser", "plasmoidviewer",
  "Xephyr", "kruler", "plasmaengineexplorer",
}

-- Ignore the tiled layout for the matching clients
tyrannical.properties.floating = {
  "xterm", "urxvt", "aterm",
  "URxvt", "XTerm", "konsole",
  "terminator", "gnome-terminal", "URxvt:Terminal",
  "URxvt:Drop", "URxvt:Tmux", "URxvt:MPD",
  "XTerm:Terminal", "Kmail:New", "Kmail:Re",
  "Dolphin:Move", "Dolphin:Copy", "Icedove:Re",
  "DownThemAll!", "Keepassx2", "Pilasengine",
  "URxvt:Emacs", "emacsclient", "URxvt:Torrent",
  "Kamerka", "MPlayer", "pinentry",
  "ksnapshot", "pinentry", "gtksu",
  "xine", "feh", "kmix",
  "kcalc", "xcalc", "yakuake",
  "Select Color$", "kruler", "kcolorchooser",
  "Paste Special", "New Form" , "Insert Picture",
  "kcharselect", "mythfrontend" , "plasmoidviewer",
  "Thunderbird:Re", "Emacs"
}

-- Make the matching clients (by classes) on top of the default layout
tyrannical.properties.ontop = {
  "Xephyr", "ksnapshot" , "kruler",
}

-- Force the matching clients (by classes) to be centered on the screen on init
tyrannical.properties.centered = {
  "kcalc", "MPV:Movie", "URxvt:Terminal",
  "URxvt:Chat", "XTerm:Terminal", "URxvt:MPD",
  "URxvt:Tmux", "Dolphin:Move", "Dolphin:Copy",
  "Kmail:New", "URxvt:Torrent", "Kmail:Re",
  "Kamerka", "URxvt:Emacs", "emacsclient",
  "Icedove:Re", "DownThemAll!", "Cutegram",
  "Keepassx2", "Thunderbird:Re", "Emacs"
}
-- Do not honor size hints request for those classes
tyrannical.properties.size_hints_honor = {
  xterm = false,
  URxvt = false,
  aterm = false,
  sauer_client = false,
  mythfrontend  = false
}

-- Menu
require("utils.menu")

-- Menubar configuration
menubar.utils.terminal = terminal -- Set the terminal for applications that require it
-- }}}

-- Widgets
-- markup
markup	= lain.util.markup
gray 	= beautiful.fg_normal
white	= beautiful.fg_focus
red	= "#EB8F8F"
green	= "#8FEB8F"

-- Clock & Date
mytextclock = lain.widgets.abase({
    timeout  = 60,
    cmd      = "date +'%a %d %b %R'",
    settings = function()
       widget:set_markup("| " .. markup(white, output))
    end
})

-- Calendar with the Clock
lain.widgets.calendar.attach(mytextclock, {
  fg = "#FFFFFF",
  bg = "#121212",
  font = beautiful.widget_font,
  font_size = "10",
})

-- /home fs
diskicon = wibox.widget.imagebox(beautiful.disk)
fswidget = lain.widgets.fs({
    partition = datapart,
    settings  = function()
        widget:set_markup(markup(gray, fs_now.used .. "% "))
    end
})
diskwidget = wibox.widget.background(diskmargin)
diskwidget:set_bgimage(beautiful.widget_bg)

-- Volume widget
volicon = wibox.widget.imagebox(beautiful.vol)
volumewidget = lain.widgets.alsa({
    settings = function()
      if volume_now.status == "off" then
        volume_now.level = volume_now.level .. "M"
      end
      widget:set_markup(markup(gray, volume_now.level .. "% "))
    end
})

-- MPD
local f = assert(io.popen("cat ~/.config/mpd/mpd.conf | grep -v '#' | grep 'music_directory' | cut -d ' ' -f2 | awk '{print $2}' | sed 's/\"//g'"))
local dir = f:read()
f:close()
mpdwidget = lain.widgets.mpd({
  music_dir = dir,
  settings = function()
    mpd_notification_preset = {
      text = string.format(
        "%s [%s] - %s\n%s", mpd_now.artist,
        mpd_now.album, mpd_now.date, mpd_now.title
      )
    }
    if mpd_now.state == "play" then
      artist = mpd_now.artist .. " > "
      title  = mpd_now.title .. " "
    elseif mpd_now.state == "pause" then
      artist = "mpd "
      title  = "paused "
    else
      artist = ""
      title  = ""
    end
    widget:set_markup(markup(white, artist) .. markup(gray, title))
  end
})

-- Active Window
focus_widget = lain.widgets.base({
    cmd = "xtitle",
    timeout = 1,
    settings = function()
      if output ~= nil and output ~= '' then
        widget:set_markup(output)
      else
        widget:set_markup('')
      end
    end
})

-- Net Info
wifiwidget = lain.widgets.base({
    cmd = "iwgetid -r",
    settings = function()
      if output ~= nil and output ~= '' then
        widget:set_markup(output)
      else
        widget:set_markup('')
      end
    end
})

local wifinotification
wifiwidget:connect_signal("mouse::enter", function()
  local f = assert(io.popen("iwgetid -ar"))
  local wifiaccesspoint = f:read()
  f:close()
  local f = io.popen("ip link show | cut -d' ' -f2,9")
  local ws = f:read("*a")
  f:close()
  local ws = ws:match("%w+: UP")
  f = assert(io.popen("iwconfig ".. ws:gsub(": UP", "") .." | grep 'Link Quality' | awk '{print $2}' | awk -F'=' '{print $2}'"))
  local wifiquality = f:read()
  f:close()
  f = io.popen("ip addr | grep 'inet ' | grep -v '127.0.0.1' | cut -d ':' -f2 | awk '{print $2}'")
  local ipaddress = f:read()
  f:close()
  wifinotification = naughty.notify({
    text = "IP: " .. ipaddress .. "\nAccess Point: " .. wifiaccesspoint .. "\nLink Quality: " .. wifiquality,
    position = "top_right",
    timeout = 0
  })
end)

wifiwidget:connect_signal("mouse::leave", function()
  if (wifinotification ~= nil) then
    naughty.destroy(wifinotification)
    wifinotification = nil
  end
end)

-- Net
netwidget = lain.widgets.net({
  settings = function()
    widget:set_markup(
      markup(gray, " ") ..
      markup(white, net_now.received) ..
      markup(gray, " / ") ..
      markup(white, net_now.sent) ..
      markup(gray, " |")
    )
  end
})

netwidget:buttons(awful.util.table.join(
    awful.button({ }, 1, function () os.execute(net) end)
))

-- Battery
baticon = wibox.widget.imagebox(beautiful.bat)
batwidget = lain.widgets.bat({
    settings = function()
      bat_perc = bat_now.perc
      perc = "%"
      if bat_now.status == "N/A" or type(bat_now.perc) ~= "number" then
        bat_perc = "Plug"
        perc = " "
        baticon:set_image(beautiful.ac)
      end

      if bat_now.status ~= "Charging" then
        if bat_now.perc > "97" then
          bat_perc = "Full"
          perc = " "
          baticon:set_image(beautiful.bat)
        elseif bat_now.perc > "50" then
          baticon:set_image(beautiful.bat)
        elseif bat_now.perc > "15" then
          baticon:set_image(beautiful.bat_low)
	 else
	    baticon:set_image(beautiful.bat_no)
        end
      end
      widget:set_markup(markup(gray, bat_perc) .. perc)
    end
})

-- Spacers
-- Separators

rbracket = wibox.widget.textbox()
rbracket:set_text(']')
lbracket = wibox.widget.textbox()
lbracket:set_text('[')
line = wibox.widget.textbox()
line:set_text('│')
space = wibox.widget.textbox()
space:set_text(' ')
mytextbox = wibox.widget.textbox()
-- }}}

-- Wibox
-- Create a wibox for each screen and add it
mywibox = {}
mybottomwibox = {}
txtlayoutbox = {}
mytaglist = {}
mytaglist.buttons = awful.util.table.join(
  awful.button({ }, 1, awful.tag.viewonly),
  awful.button({ modkey }, 1, awful.client.movetotag),
  awful.button({ }, 3, awful.tag.viewtoggle),
  awful.button({ modkey }, 3, awful.client.toggletag),
  awful.button({ }, 4, function(t) awful.tag.viewnext(awful.tag.getscreen(t)) end),
  awful.button({ }, 5, function(t) awful.tag.viewprev(awful.tag.getscreen(t)) end)
)
mytasklist = {}
mytasklist.buttons = awful.util.table.join(
  awful.button({ }, 1, function (c)
    if c == client.focus then
      c.minimized = true
    else
      c.minimized = false
      if not c:isvisible() then
        awful.tag.viewonly(c:tags()[1])
      end
        client.focus = c
        c:raise()
    end
  end),
  awful.button({ }, 3, function ()
    if instance then
      instance:hide()
      instance = nil
    else
      instance = awful.menu.clients({ width=250 })
    end
  end),
  awful.button({ }, 4, function ()
    awful.client.focus.byidx(1)
    if client.focus then
      client.focus:raise()
    end
  end),
  awful.button({ }, 5, function ()
    awful.client.focus.byidx(-1)
    if client.focus then
      client.focus:raise()
    end
  end)
)

function updatelayoutbox(layout, s)
  local screen = s or 1
  local txt_l = beautiful["layout_txt_" .. awful.layout.getname(awful.layout.get(screen))] or ""
  layout:set_text(txt_l)
end

for s = 1, screen.count() do

    -- Create an imagebox widget which will contains an icon indicating which layout we're using.
    -- We need one layoutbox per screen.
	txtlayoutbox[s] = wibox.widget.textbox(beautiful["layout_txt_" .. awful.layout.getname(awful.layout.get(s))])
  awful.tag.attached_connect_signal(s, "property::selected", function ()
    updatelayoutbox(txtlayoutbox[s], s)
  end)
  awful.tag.attached_connect_signal(s, "property::layout", function ()
    updatelayoutbox(txtlayoutbox[s], s)
  end)
  txtlayoutbox[s]:buttons(awful.util.table.join(
    awful.button({}, 1, function() awful.layout.inc(layouts, 1) end),
    awful.button({}, 3, function() awful.layout.inc(layouts, -1) end),
    awful.button({}, 4, function() awful.layout.inc(layouts, 1) end),
    awful.button({}, 5, function() awful.layout.inc(layouts, -1) end)))
  -- Create a taglist widget
  mytaglist[s] = awful.widget.taglist(s, awful.widget.taglist.filter.all, mytaglist.buttons)
  -- Create a tasklist widget
  mytasklist[s] = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, mytasklist.buttons)
  -- Create the wibox
  mywibox[s] = awful.wibox({ position = "top", screen = s, height = 18 })
  left_layout = wibox.layout.fixed.horizontal()
  left_layout:add(txtlayoutbox[s])
  left_layout:add(space)
  left_layout:add(mytaglist[s])
  left_layout:add(space)
  center_layout = wibox.layout.fixed.horizontal()
  center_layout:add(mpdwidget)
  -- center_layout:add(focus_widget)
  right_layout = wibox.layout.fixed.horizontal()
  right_layout:add(space)
  right_layout:add(space)
  right_layout:add(wifiwidget)
  right_layout:add(netwidget)
  right_layout:add(space)
  right_layout:add(diskicon)
  right_layout:add(fswidget)
  right_layout:add(space)
  right_layout:add(baticon)
  right_layout:add(batwidget)
  right_layout:add(space)
  right_layout:add(volicon)
  right_layout:add(volumewidget)
  right_layout:add(space)
  right_layout:add(mytextclock)
  local layout = wibox.layout.align.horizontal()
  layout:set_left(left_layout)
  layout:set_middle(center_layout)
  layout:set_right(right_layout)
  mywibox[s]:set_widget(layout)
  mybottomwibox[s] = awful.wibox({ position = "bottom", screen = s, height = 16 })
  mybottomwibox[s].visible = false
  bottom_right_layout = wibox.layout.fixed.horizontal()
  bottom_right_layout:add(space)
  bottom_layout = wibox.layout.align.horizontal()
  bottom_layout:set_middle(mytasklist[s])
  bottom_layout:set_right(bottom_right_layout)
  mybottomwibox[s]:set_widget(bottom_layout)
end
-- }}}

-- Mouse bindings
root.buttons(awful.util.table.join(
  awful.button({ }, 4, awful.tag.viewnext),
  awful.button({ }, 5, awful.tag.viewprev)
))
-- }}}

-- Key bindings
globalkeys = awful.util.table.join(
  awful.key({modkey}, "Left", awful.tag.viewprev),
  awful.key({modkey}, "Right", awful.tag.viewnext),
  awful.key({modkey}, "Escape", awful.tag.history.restore),
  awful.key({modkey}, "j", function ()
      awful.client.focus.byidx( 1)
      if client.focus then
        client.focus:raise()
      end
                           end
  ),
  awful.key({modkey}, "k", function ()
      awful.client.focus.byidx(-1)
      if client.focus then
        client.focus:raise()
      end
                           end
  ),
  awful.key({modkey}, "w", function ()
      mymainmenu:show()
                           end
  ),
  -- Layout manipulation
  awful.key({modkey, "Shift"}, "j", function ()
      awful.client.swap.byidx(  1)
                                    end
  ),
  awful.key({ modkey, "Shift"   }, "k", function () awful.client.swap.byidx( -1)    end),
  awful.key({ modkey, "Control" }, "j", function () awful.screen.focus_relative( 1) end),
  awful.key({ modkey, "Control" }, "k", function () awful.screen.focus_relative(-1) end),
  awful.key({ modkey,           }, "u", awful.client.urgent.jumpto),
  awful.key({ modkey,           }, "Tab",
    function ()
      awful.client.focus.history.previous()
      if client.focus then
        client.focus:raise()
      end
  end),

  -- ScreenShot
  awful.key({ modkey, "Shift"  }, "p",      function() awful.util.spawn(scriptdir .. "/screenshot") end),

  -- Show/Hide Wibox
  awful.key({ modkey,           }, "F1", function ()
      mywibox[mouse.screen].visible = not mywibox[mouse.screen].visible
  end),

  awful.key({ modkey,           }, "F2", function ()
      mybottomwibox[mouse.screen].visible = not mybottomwibox[mouse.screen].visible
  end),

  -- Revelation
  awful.key({modkey, "Shift"    }, "e",  revelation ),

  -- Standard program
  awful.key({ modkey,           }, "p",     function () awful.util.spawn(music)  end),
  awful.key({ modkey,           }, "t",     function () awful.util.spawn(fileman) end),
  awful.key({ modkey,           }, "f",     function () awful.util.spawn(cfileman) end),
  awful.key({ modkey,           }, "b",     function () awful.util.spawn(browser) end),
  awful.key({ modkey,           }, "i",     function () awful.util.spawn(chat) end),
  -- awful.key({ modkey,           }, "e",     function () awful.util.spawn(eter) end),
  awful.key({ modkey,           }, "e",     function () awful.util.spawn(scriptdir .. "/demacs") end),
  awful.key({ modkey,           }, "d",     function () awful.util.spawn(torrent) end),
  awful.key({ modkey,           }, "Return",function () awful.util.spawn(terminal) end),
  awful.key({ modkey, "Control" }, "Return",function () awful.util.spawn(tmux) end),
  awful.key({ modkey, "Control" }, "r", awesome.restart),
  awful.key({ modkey, "Shift"   }, "q", awesome.quit),

  -- Record a Screencast
  awful.key({ modkey,       }, "F7",      function() awful.util.spawn(scriptdir .. "/start_screencast") end),
  awful.key({ modkey,       }, "F8",      function() awful.util.spawn(scriptdir .. "/stop_screencast") end),

  -- attach terminal to F12
  awful.key({               }, "F12",
    function ()
      drop.toggle(ddterminal, "left", "top", 0.8, 0.75)
  end),

  awful.key({ modkey,    }, "F12",
    function ()
      drop.attach(ddterminal)
  end),
  -- Toggle Systray
  awful.key({ modkey,    }, "s", function() minitray.toggle() end ),

  -- Volume control
  awful.key({ altkey }, "Up",
    function ()
      os.execute("pamixer -i 1")
      --os.execute(string.format("amixer set %s 1%%+", volume.channel))
      volume.update()
  end),
  awful.key({ altkey }, "Down",
    function ()
      --os.execute(string.format("amixer set %s 1%%-", volume.channel))
      os.execute("pamixer -d 1")
      volume.update()
  end),
  awful.key({ altkey }, "m",
    function ()
      os.execute("pamixer -t")
      --os.execute(string.format("amixer set %s toggle", volume.channel))
      volume.update()
  end),
  awful.key({ altkey, "Control" }, "m",
    function ()
      os.execute("pamixer --allow-boost")
      --os.execute(string.format("amixer set %s 100%%", volume.channel))
      volume.update()
  end),

  -- MPD control
  awful.key({ altkey, "Control" }, "Up",
    function ()
      awful.util.spawn_with_shell("mpc toggle || ncmpc toggle || pms toggle")
  end),

  awful.key({ altkey, "Control" }, "Down",
    function ()
      awful.util.spawn_with_shell("mpc stop || ncmpc stop || pms stop")
  end),
  awful.key({ altkey, "Control" }, "Left",
    function ()
      awful.util.spawn_with_shell("mpc prev || ncmpc prev || pms prev")
  end),
  awful.key({ altkey, "Control" }, "Right",
    function ()
      awful.util.spawn_with_shell("mpc next || ncmpc next || pms next")
  end),

  awful.key({ modkey,           }, "l",     function () awful.tag.incmwfact( 0.05)    end),
  awful.key({ modkey,           }, "h",     function () awful.tag.incmwfact(-0.05)    end),
  awful.key({ modkey, "Shift"   }, "h",     function () awful.tag.incnmaster( 1)      end),
  awful.key({ modkey, "Shift"   }, "l",     function () awful.tag.incnmaster(-1)      end),
  awful.key({ modkey, "Control" }, "h",     function () awful.tag.incncol( 1)         end),
  awful.key({ modkey, "Control" }, "l",     function () awful.tag.incncol(-1)         end),
  awful.key({ modkey,           }, "space", function () awful.layout.inc(layouts,  1) end),
  awful.key({ modkey, "Shift"   }, "space", function () awful.layout.inc(layouts, -1) end),

  awful.key({ modkey, "Control" }, "n", awful.client.restore),

  -- Show Open Window's
  awful.key({ altkey            }, "Tab",
    function ()
      menu = {
        theme = {
          width = 300,
          border = 1,
          border_color = beautiful.border_focus,
          bg_normal = "#121212"
        }
	    }
      menu.items = clsmenu()
      local m = awful.menu(menu)
      m:show()
  end),
	-- Show Open DropDown Terminal

  awful.key({ altkey, "Control" }, "Tab",
    function ()
      menu = {
	      theme = {
          width = 300,
          border = 1,
          border_color = beautiful.border_focus,
          bg_normal = "#121212"
	      }
      }
      menu.items = clsmenu_drop()
      local m = awful.menu(menu)
      m:show()
  end),
  -- Prompt
  -- awful.key({ modkey },            "r",     function () mypromptbox[mouse.screen]:run() end),
  awful.key({ modkey            }, "r",
    function()
      os.execute(
        "dmenu_run -b -i -p 'Run:" ..
          "' -nb '" .. beautiful.bg_dmenu_normal ..
          "' -nf '" .. beautiful.fg_normal ..
          "' -sb '" .. beautiful.bg_dmenu_focus  ..
          "' -sf '" .. beautiful.fg_focus  ..
          "' -fn '" .. beautiful.dfont .. "'")
  end),

  awful.key({ modkey }, "x",
    function ()
      awful.prompt.run({ prompt = "Run Lua code: " },
        mypromptbox[mouse.screen].widget,
        awful.util.eval, nil,
        awful.util.getdir("cache") .. "/history_eval")
  end)
  -- Menubar
  --awful.key({ modkey }, "p", function() menubar.show() end)
)

clientkeys = awful.util.table.join(
    awful.key({ modkey, "Shift"   }, "f",      function (c) c.fullscreen = not c.fullscreen  end),
    awful.key({ modkey, "Shift"   }, "c",      function (c) c:kill()                         end),
    awful.key({ modkey, "Control" }, "space",  awful.client.floating.toggle                     ),
    awful.key({ modkey, "Control" }, "Return", function (c) c:swap(awful.client.getmaster()) end),
    awful.key({ modkey,           }, "o",      awful.client.movetoscreen                        ),
    awful.key({ modkey,           }, "t",      function (c) c.ontop = not c.ontop            end),
    awful.key({ modkey,           }, "n",
        function (c)
            -- The client currently has the input focus, so it cannot be
            -- minimized, since minimized clients can't have the focus.
            c.minimized = true
        end),
    awful.key({ modkey,           }, "m",
        function (c)
            c.maximized_horizontal = not c.maximized_horizontal
            c.maximized_vertical   = not c.maximized_vertical
        end)
)

-- Bind all key numbers to tags.
-- Be careful: we use keycodes to make it works on any keyboard layout.
-- This should map on the top row of your keyboard, usually 1 to 9.
for i = 1, 9 do
    globalkeys = awful.util.table.join(globalkeys,
        awful.key({ modkey }, "#" .. i + 9,
                  function ()
                        local screen = mouse.screen
                        local tag = awful.tag.gettags(screen)[i]
                        if tag then
                           awful.tag.viewonly(tag)
                        end
                  end),
        awful.key({ modkey, "Control" }, "#" .. i + 9,
                  function ()
                      local screen = mouse.screen
                      local tag = awful.tag.gettags(screen)[i]
                      if tag then
                         awful.tag.viewtoggle(tag)
                      end
                  end),
        awful.key({ modkey, "Shift" }, "#" .. i + 9,
                  function ()
                      local tag = awful.tag.gettags(client.focus.screen)[i]
                      if client.focus and tag then
                          awful.client.movetotag(tag)
                     end
                  end),
        awful.key({ modkey, "Control", "Shift" }, "#" .. i + 9,
                  function ()
                      local tag = awful.tag.gettags(client.focus.screen)[i]
                      if client.focus and tag then
                          awful.client.toggletag(tag)
                      end
                  end))
end

clientbuttons = awful.util.table.join(
    awful.button({ }, 1, function (c) client.focus = c; c:raise() end),
    awful.button({ modkey }, 1, awful.mouse.client.move),
    awful.button({ modkey }, 3, awful.mouse.client.resize))

-- Set keys

root.keys(globalkeys)

-- }}}

-- {{{ Rules
awful.rules.rules = {
    -- All clients will match this rule.
    { rule = { },
      properties = { border_width = beautiful.border_width,
                     border_color = beautiful.border_normal,
                     focus = awful.client.focus.filter,
                     keys = clientkeys,
                     buttons = clientbuttons } },
    { rule = { class = "MPlayer" },
      properties = { floating = true } },
    { rule = { class = "pinentry" },
      properties = { floating = true } },
    { rule = { class = "gimp" },
      properties = { floating = true } },
    {
        rule = { class = "URxvt", name = "Terminal" },
        callback = function (c)
            awful.client.property.set(c, "overwrite_class", "URxvt:Terminal")
        end
    },
    {
        rule = { class = "URxvt", name = "Drop-Terminal" },
        callback = function (c)
            awful.client.property.set(c, "overwrite_class", "URxvt:Drop")
        end
    },
    {
        rule = { class = "URxvt", name = "Ranger" },
        callback = function (c)
            awful.client.property.set(c, "overwrite_class", "URxvt:Ranger")
        end
    },
    {
        rule = { class = "URxvt", name = "Tmux" },
        callback = function (c)
            awful.client.property.set(c, "overwrite_class", "URxvt:Tmux")
        end
    },
    {
       rule = { class = "URxvt", name = "Torrent" },
       callback = function (c)
          awful.client.property.set(c, "overwrite_class", "URxvt:Torrent")
        end
    },
    {
        rule = { class = "URxvt", name = "Chat" },
        callback = function (c)
            awful.client.property.set(c, "overwrite_class", "URxvt:Chat")
        end
    },
    { rule = { class = "URxvt", name = "Music" },
      callback = function (c)
            awful.client.property.set(c, "overwrite_class", "URxvt:MPD")
        end
    },
    { rule = { class = "URxvt", name = "emacs" },
      callback = function(c)
         awful.client.property.set(c, "overwrite_class", "URxvt:Emacs")
        end
    },
    {
        rule = { class = "XTerm" },
        callback = function (c)
            awful.client.property.set(c, "overwrite_class", "XTerm:Terminal")
        end
    },
    {
        rule = { class = "mpv" },
        callback = function (c)
            awful.client.property.set(c, "overwrite_class", "MPV:Movie")
        end
    },
    { rule = { class = "Kmail", name = "sin nombre" },
      callback = function (c)
            awful.client.property.set(c, "overwrite_class", "Kmail:New")
        end
    },
    { rule = { class = "Kmail", name = "Re:" },
      callback = function (c)
            awful.client.property.set(c, "overwrite_class", "Kmail:Re")
        end
    },

    { rule = { class = "Thunderbird", name = "Redacción: " },
      callback = function (c)
            awful.client.property.set(c, "overwrite_class", "Thunderbird:Re")
        end
    },

    { rule = { class = "Icedove", name = "Redacción: " },
      callback = function (c)
            awful.client.property.set(c, "overwrite_class", "Icedove:Re")
        end
    },

    {
		rule = { class = "Dolphin", name = "Copiando " },
        callback = function (c)
            awful.client.property.set(c, "overwrite_class", "Dolphin:Copy")
        end
    },

    {
		rule = { class = "Dolphin", name = "Moviendo " },
        callback = function (c)
            awful.client.property.set(c, "overwrite_class", "Dolphin:Move")
        end
    },
}
-- }}}

-- {{{ Signals
-- Signal function to execute when a new client appears.
client.connect_signal("manage", function (c, startup)
    -- Enable sloppy focus
    c:connect_signal("mouse::enter", function(c)
        if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier
            and awful.client.focus.filter(c) then
            client.focus = c
        end
    end)

    if not startup then
        -- Set the windows at the slave,
        -- i.e. put it at the end of others instead of setting it master.
        -- awful.client.setslave(c)

        -- Put windows in a smart way, only if they does not set an initial position.
        if not c.size_hints.user_position and not c.size_hints.program_position then
            awful.placement.no_overlap(c)
            awful.placement.no_offscreen(c)
        end
    end

    local titlebars_enabled = false
    if titlebars_enabled and (c.type == "normal" or c.type == "dialog") then
        -- Widgets that are aligned to the left
        local left_layout = wibox.layout.fixed.horizontal()
        left_layout:add(awful.titlebar.widget.iconwidget(c))

        -- Widgets that are aligned to the right
        local right_layout = wibox.layout.fixed.horizontal()
        right_layout:add(awful.titlebar.widget.floatingbutton(c))
        right_layout:add(awful.titlebar.widget.maximizedbutton(c))
        right_layout:add(awful.titlebar.widget.stickybutton(c))
        right_layout:add(awful.titlebar.widget.ontopbutton(c))
        right_layout:add(awful.titlebar.widget.closebutton(c))

        -- The title goes in the middle
        local title = awful.titlebar.widget.titlewidget(c)
        title:buttons(awful.util.table.join(
                awful.button({ }, 1, function()
                    client.focus = c
                    c:raise()
                    awful.mouse.client.move(c)
                end),
                awful.button({ }, 3, function()
                    client.focus = c
                    c:raise()
                    awful.mouse.client.resize(c)
                end)
                ))

        -- Now bring it all together
        local layout = wibox.layout.align.horizontal()
        layout:set_left(left_layout)
        layout:set_right(right_layout)
        layout:set_middle(title)

        awful.titlebar(c):set_widget(layout)
    end
end)

client.connect_signal("focus", function(c) c.border_color = beautiful.border_focus end)
client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end)
